

let socket = null;
let isCreate = false;
let isConnect = false;
let heartbeatTimer = 1;
let reconnectTimer = 1;
let isInitiative = false;
let againTime = 3;
let timeoutNumber = 3;

export const initSocket = (url)=>{
	if(isConnect) {
		console.log('####already connect');
		return;
	}
	socket = uni.connectSocket({
	  url: url,
	  header: {
		'content-type': 'application/json'
	  },
	  success: (res) => {
		isCreate = true
		console.log(res)
	  },
	  fail: (rej) => {
		console.error(rej)
		isCreate = false
	  }
	})
	createSocket();
}

const createSocket = ()=>{
	if (isCreate) {
	  console.log('WebSocket 开始初始化')
	  // 监听 WebSocket 连接打开事件
	  try {
		socket.onOpen(() => {
		  console.log('WebSocket 连接成功');
		  isConnect = true;
		  clearInterval(heartbeatTimer);
		  clearTimeout(reconnectTimer);
		  // 打开心跳检测
		  heartbeatCheck();
		})
		// 监听 WebSocket 接受到服务器的消息事件
		socket.onMessage((res) => {
		  let data = JSON.parse(res.data);
		  
		  if(data.msgType==='Jar'){
		  	//console.log('收到服务器内容：',data);
		  	uni.$emit('update:monitor_jar',data.data);
		  }else if(data.msgType==='JobAll'){
		  	console.log('3333333,',data);
		  }else if(data.msgType==='Job'){
		  	
		  }
		})
		// 监听 WebSocket 连接关闭事件
		socket.onClose(() => {
		  console.log('WebSocket 关闭了');
		  isConnect = false;
		  reconnect();
		})
		// 监听 WebSocket 错误事件
		socket.onError((res) => {
		  console.log('WebSocket 出错了');
		  console.log(res);
		  isInitiative = false;
		})
	  } catch (error) {
		console.log(error);
	  }
	} else {
	  console.log('WebSocket 初始化失败!')
	}
}

const heartbeatCheck = ()=>{
	console.log('开启心跳')
	let data = { state: 1, method: 'heartbeat' }
	heartbeatTimer = setInterval(() => {
	  sendMsg(data);
	}, timeoutNumber * 1000);
}

const sendMsg = (value)=>{
	const param = JSON.stringify(value)
	return new Promise((resolve, reject) => {
	  socket.send({
		data: param,
		success() {
		  console.log('消息发送成功')
		  resolve(true)
		},
		fail(error) {
		  console.log('消息发送失败')
		  reject(error)
		}
	  })
	})
}

const reconnect = ()=>{
	// 停止发送心跳
	clearTimeout(reconnectTimer)
	clearInterval(heartbeatTimer)
	// 如果不是人为关闭的话，进行重连
	if (!isInitiative) {
	  
	}
	
	reconnectTimer = setTimeout(() => {
			initSocket();
	}, againTime * 1000)
}

// const closeSocket = ()=>{
// 	this.socket.close({
// 	  '原因',
// 	  success() {
// 		this.isCreate = false
// 		this.isConnect = false
// 		this.isInitiative = true
// 		this.socketExamples = null
// 		clearInterval(this.heartbeatTimer)
// 		clearTimeout(this.reconnectTimer)
// 		console.log('关闭 WebSocket 成功')
// 	  },
// 	  fail() {
// 		console.log('关闭 WebSocket 失败')
// 	  }
// 	})
// }